package P94.P102;

import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author DJ同学
 * @Date 2021/2/22 22:54
 * @Version 1.0
 * @Name 二叉树的层序遍历
 * @Problem https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 * @Idea BFS + 分层节点
 */
public class Solution2 {
    @Test
    public void test01(){
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.left.left = null;
        root.left.right = null;
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.left.left = null;
        root.right.left.right = null;
        root.right.right = new TreeNode(7);
        root.right.right.left = null;
        root.right.right.right = null;
        levelOrder(root);
        System.out.println(root);
    }
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root==null) return res;
        //存放节点队列
        Queue<TreeNode> queue = new LinkedList<>();
        //分层值
        TreeNode point = new TreeNode(Integer.MIN_VALUE);
        //放入根节点
        queue.offer(root);
        //放入分层值
        queue.offer(point);
        List<Integer> temp = new ArrayList<>();
        while(!queue.isEmpty()){
            //获得堆顶节点
            TreeNode cur = queue.peek();
            if(cur==point){
                queue.poll();
                res.add(temp);
                temp = new ArrayList<>();
                if(!queue.isEmpty()){ //注意点
                    queue.offer(point);
                }
            }else{
                temp.add(cur.val);
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
                queue.poll();
            }
        }
        return res;
    }
}
